package com.yang.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.yang.User;
import com.yang.dao.FielDao;
import com.yang.entity.Fiel;

@SuppressWarnings("deprecation")
public class FileAction extends ActionSupport implements SessionAware{

	private static final long serialVersionUID = -1669542551147918284L;
	private String name;
	private File file;
	private String fileFileName;
	private String fileContentType;
	private FielDao fd = new FielDao();
	private String code;
	private int fileId;
	private Fiel fiel;
	private String father;
	private int son;
	private String id;
	private InputStream is;
	@SuppressWarnings("unchecked")
	private Map<String, Object> session=(Map<String, Object>) ActionContext.getContext().get(ActionContext.SESSION);
	private User user=(User) session.get("user");
	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
	public String toList() throws Exception {
		List<Fiel> list=fd.getList(Integer.parseInt(father==null?"0":father));
		fiel=new Fiel();
		fiel.setId(0);
		fiel.setName("...");
		session.put("fiel", fiel);
		session.put("list", list);
		return SUCCESS;
	}
	public String findMd() throws Exception {
		List<Fiel> list=fd.findByMDs(fiel.getMd());
		session.put("list", list);
		return SUCCESS;
	}
	public String toListSon() throws Exception {
		List<Fiel> list=fd.getList(fileId);
		fiel=fd.getFile(fileId);
		if(fiel==null){
			fiel=new Fiel();
			fiel.setId(0);
			fiel.setName("...");
		}
		session.put("fiel", fiel);
		session.put("list", list);
		return SUCCESS;
	}
	public String makedir() throws Exception {
		/*List<Fiel> list=fd.getList();
		session.put("list", list);*/
		int fa=Integer.parseInt(father);
		fiel=new Fiel();
		fiel.setContentType("feil");
		fiel.setUserid(user.getId());
		fiel.setFather(fa);
		fiel.setLength(0);
		fiel.setName(name);
		fiel.setRoundName(u.toString());
		fiel.setSon(-1);
		fiel.setTime(time);
		return fd.insert(fiel)?SUCCESS:ERROR;
	}
	
	UUID u = UUID.randomUUID();
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String time = df.format(new Date());
	
	public String updatefiel() throws Exception{
		boolean b=fd.newName(Integer.parseInt(id),name);
		if(b){
			is=new StringBufferInputStream("ok");
			return SUCCESS;
		}else{
			is=new StringBufferInputStream("error");
			return ERROR;
		}
	}
	
	public String upload() throws Exception {
		String type = fileFileName.substring(fileFileName.lastIndexOf(".") + 1);
		String roundName = u.toString() + "." + type;
		fiel = new Fiel();
		long length = file.length();
		fiel.setName(fileFileName);
		fiel.setUserid(user.getId());
		fiel.setContentType(fileContentType);
		fiel.setRoundName(roundName);
		fiel.setLength(length);
		fiel.setTime(time);
		int fa=Integer.parseInt(father==null?"0":father);
		
		fiel.setFather(fa);
		fiel.setSon(-2);
		InputStream is=new FileInputStream(file);
		String md5=DigestUtils.md5Hex(is);
		is.close();
		Fiel bmd=fd.findByMD5(md5);
		fiel.setMd(md5);
		if(bmd!=null){
			fiel.setRoundName(bmd.getRoundName());
		}
		if(fa!=0){
			Fiel fielfather=fd.getFile(fa);
			if(fielfather.getSon()!=-2){
				fielfather.setSon(-4);
				fielfather.setLength(fielfather.getLength()+length);
			}
			boolean b=fd.update(fielfather);
		}
		boolean bo = file.length()<1073741824?fd.insert(fiel):false;
		if (bo&&bmd==null) {
			is=new FileInputStream(file);
			BufferedInputStream bis = new BufferedInputStream(is);
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(ServletActionContext.getServletContext().getRealPath("/")  + "download/"+ roundName));
			int len = 0;
			byte[] b = new byte[1024];
			while ((len = bis.read(b)) != -1) {
				bos.write(b, 0, len);
			}
			bos.flush();
			bos.close();
			bis.close();
			return SUCCESS;
		}else if(bo&bmd!=null){
			return SUCCESS;
		}
		throw new Exception("文件太大");
	}
	public String download() throws Exception{
		return SUCCESS;
	}
	public String dropAllData() throws Exception{
		boolean boo=fd.deleteAllData();
		String pathname = ServletActionContext.getServletContext().getRealPath("/") + "download";
		File file=new File(pathname);
		List<Boolean> list=new ArrayList<Boolean>();
		for (String f : file.list()) {
			File ff=new File(pathname+"/"+f);
			try {
				boolean b=ff.delete();
				if(!b){
					list.add(b);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return boo&&list.size()==0?SUCCESS:ERROR;
	}
	public InputStream getInputStream() throws FileNotFoundException, UnsupportedEncodingException{
		fiel=fd.getFile(fileId);
		fiel.setName(new String(fiel.getName().getBytes("utf-8"),"iso8859-1"));
		String fileName=fiel.getRoundName();
		String filePath = ServletActionContext.getServletContext().getRealPath("/") + "download/" + fileName;
		InputStream stream = new FileInputStream(new File(filePath));
		return stream;
	}
	public String delfiel(){
		int power=user.getPower();
		boolean result=false;
		if(power==1){
			result=fd.update(Integer.parseInt(id),2);
		}else if(power==4){
			result=fd.update(Integer.parseInt(id),4);
		}else if(power==8){
			result=fd.delFile(Integer.parseInt(id));
		}
		is=new StringBufferInputStream(result?"ok":"error");
		return result?SUCCESS:ERROR;
	}
	public String getName() {
		return name;
	}

	public File getFile() {
		return file;
	}

	public String getFileContentType() {
		return fileContentType;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public int getFileId() {
		return fileId;
	}

	public void setFileId(int fileId) {
		this.fileId = fileId;
	}

	public Fiel getFiel() {
		return fiel;
	}

	public void setFiel(Fiel fiel) {
		this.fiel = fiel;
	}
	@Override
	public void setSession(Map<String, Object> session) {
		this.session=session;
	}
	public String getFather() {
		return father;
	}
	public int getSon() {
		return son;
	}
	public void setFather(String father) {
		this.father = father;
	}
	public void setSon(int son) {
		this.son = son;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public InputStream getIs() {
		return is;
	}
	
}